﻿
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.SignalR;
using System.Security.Principal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace WebOSCore.Models
{
    public class ChatHub : Hub
    {
        public static List<OnlineUser> ConnectedUsers = new List<OnlineUser>();

        public async Task ReceiveMessage(string username, string avatar, string id, string type, string my, string message)
        {
            string fromUserId = Context.ConnectionId;

            var toUser = ConnectedUsers.FirstOrDefault(x => x.id == id);

            // Clients.Client(toUser.ConnectionId).receivePrivateMessage(fromUser.UserID, fromUser.UserName, message, fromUser.Avatar, "friend");
            var user = Context.User;
         
            var userid = user.Claims.FirstOrDefault(c => c.Type == "id").Value;
            if (toUser != null)
            {
                await Clients.Client(toUser.ConnectionId).SendAsync("ReceiveMessage", toUser.username, toUser.avatar, toUser.id, "friend", message);
            }
            // await Clients.All.SendAsync("ReceiveMessage", username, avatar, id, type, message);


            // send to caller user



        }

        public override async Task OnConnectedAsync()
        {
           
               var id = Context.ConnectionId;
            var user = Context.User;
       
            var userid = user.Claims.FirstOrDefault(c => c.Type == "id").Value;
            var zx = ConnectedUsers.FirstOrDefault(c => c.id == userid);
            if (zx != null)
            {
                var lj = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == id);
                if (lj == null)
                {
                    //先移除
                    ConnectedUsers.Remove(zx);
                    //链接
                    ConnectedUsers.Add(new OnlineUser { ConnectionId = id, id = userid, username = user.Identity.Name });
                }
            }
            else
            {
                ConnectedUsers.Add(new OnlineUser { ConnectionId = id, id = userid, username = user.Identity.Name });
            }
            //var http = Context.GetHttpContext();
            //var client = new OnlineClient()
            //{
            //    NickName = http.Request.Query["nickName"],
            //    Avatar = http.Request.Query["avatar"]
            //};
            //lock (SyncObj)
            //{
            //    OnlineClients[Context.ConnectionId] = client;
            //}
            await base.OnConnectedAsync();
            //await Groups.AddToGroupAsync(Context.ConnectionId, ChatName);
            //await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用户{client.NickName}加入了群聊");
            //   await Clients.Client(Context.ConnectionId).SendAsync("system", $"成功加入{ChatName}");
        }

        /// <summary>
        /// 客户端断开连接时触发
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>


        public override async Task OnDisconnectedAsync(Exception exception)
        {
            Guid gd = Guid.Empty;
           var  message = "你已经掉线请重新登陆！";
            var id = Context.ConnectionId;
            var toUser = ConnectedUsers.FirstOrDefault(c => c.ConnectionId == id);

            //通知其他客户端有人下线
            await Clients.Others.SendAsync("UserOffline", toUser.username);
 
            if (toUser != null) {
            await Clients.Client(toUser.ConnectionId).SendAsync("receivePrivateMessage", toUser.username, toUser.avatar, gd.ToString(), "friend", message);
                //移除掉线用户
                ConnectedUsers.Remove(toUser);
            }

            await base.OnDisconnectedAsync(exception);
            //bool isRemoved;
            //OnlineClient client;
            //lock (SyncObj)
            //{
            //    isRemoved = OnlineClients.TryRemove(Context.ConnectionId, out client);
            //}
            //await Groups.RemoveFromGroupAsync(Context.ConnectionId, ChatName);
            //if (isRemoved)
            //{
            //    await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用户{client.NickName}退出了群聊");
            //}
        }
        /// <summary>
        /// /链接时调用
        /// </summary>
        /// <returns></returns>

        /// <summary>
        /// 发送私聊
        /// </summary>
        /// <param name="toUserId">接收方用户连接ID</param>
        /// <param name="message">内容</param>
        public async Task SendSysMessage(string toUserId, string message)
        {


            var toUser = ConnectedUsers.FirstOrDefault(x => x.id == toUserId);
            var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUser.ConnectionId);

            if (toUser != null && fromUser != null)
            {
                await Clients.Client(toUser.ConnectionId).SendAsync("receivePrivateMessage", toUser.username, toUser.avatar, fromUser.id, "friend", message);

                // send to caller user
                //Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
            }
            else
            {
                //表示对方不在线
                // Clients.Caller.SendCoreAsync();
            }
        }

        public async Task SendPrivateMessage(string toUserId, string message)
        {
            string fromUserId = Context.ConnectionId;

            var toUser = ConnectedUsers.FirstOrDefault(x => x.id == toUserId);
            var ss=Context.User.Claims.FirstOrDefault(c => c.Type == "id").Value;
            var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

            if (toUser != null && fromUser != null)
            {
                await Clients.Client(toUser.ConnectionId).SendAsync("receivePrivateMessage", toUser.username, toUser.avatar, fromUser.id, "friend", message);

                // send to caller user
                //Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
            }
            else
            {
                //表示对方不在线
                // Clients.Caller.SendAsync();
            }
        }


    }

    public class OnlineUser
    {
        /// <summary>
        /// 连接ID
        /// </summary>
        public string ConnectionId { get; set; }
        /// <summary>
        /// 用户ID
        /// </summary>


        public string username { get; set; }
        /// <summary>
        /// 
        /// </summary>

        public string id { get; set; }
        /// <summary>
        /// 
        /// </summary>

        public string avatar { get; set; }
        /// <summary>
        /// 这些都是测试数据，实际使用请严格按照该格式返回
        /// </summary>

        public string sign { get; set; }
    }
}
